package com.zyd.blog.core.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author gxing
 * @desc
 * @date 2020/10/15
 */
@Slf4j
public class WebSocketSessionConfigurator extends Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        log.info("HttpSessionClassName:{}, httpSessionObj:{}", HttpSession.class.getName(), httpSession);
        // 通过NGINX代理的WS, HttpSession 可能为空
        if (!ObjectUtils.isEmpty(httpSession)) {
            config.getUserProperties().put(HttpSession.class.getName(), request.getHttpSession());
        }
        Map<String, List<String>> headers = request.getHeaders();
//        log.info("请求头:{}", JSON.toJSONString(headers));
        List<String> realIpList = new ArrayList<>();
        realIpList = headers.get("x-real-ip");
        if (CollectionUtils.isEmpty(realIpList)) {
            realIpList = headers.get("X-Forwarded-For");
        }

        if (CollectionUtils.isNotEmpty(realIpList)) {
            config.getUserProperties().put("realAddress", realIpList.get(0));
        }
    }
}
